package com.boardour.wifip2p.receiver;

import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;

import com.boardour.wifip2p.WifiP2pCommon;

import java.net.InetAddress;

/**
 * 连接地址管理
 */
public class AddressManager {
    private static final AddressManager instance = new AddressManager();
    private WifiP2pDevice wifiP2pDevice;
    private InetAddress address;
    private boolean isGroupOwner;

    public static AddressManager getInstance() {
        return instance;
    }

    private AddressManager() {
    }

    public void onWifiP2pDeviceChanged(WifiP2pDevice wifiP2pDevice) {
        this.wifiP2pDevice = wifiP2pDevice;
        if (wifiP2pDevice.status == WifiP2pDevice.CONNECTED) {
            initAddress();
        } else {
            address = null;
        }
    }

    private void initAddress() {
        WifiP2pCommon.getInstance().requestConnectionInfo(new WifiP2pManager.ConnectionInfoListener() {
            @Override
            public void onConnectionInfoAvailable(WifiP2pInfo info) {
                AddressManager.this.isGroupOwner = info.isGroupOwner;
                InetAddress address = info.groupOwnerAddress;
                if (address == null) {
                    onWifiP2pDeviceChanged(wifiP2pDevice);
                } else {
                    AddressManager.this.address = address;
                }
            }
        });
    }

    public InetAddress getAddress() {
        return address;
    }

    public String getHostName() {
        if (address == null) {
            return null;
        }
        String str = address.toString();
        return str.substring(str.lastIndexOf("/") + 1);
    }

    public boolean isGroupOwner() {
        return isGroupOwner;
    }
}
